﻿using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using System.Windows.Forms;

namespace Administracja
{
    public partial class Logowanie : Form
    {
        public bool IsOk { get; private set; }

        public Logowanie()
        {
            InitializeComponent();
            WczytajPlik();
        }

        private void ZalogujClick(object sender, EventArgs e)
        {
            const string user = "81f7eeab96c8eb939b02d06e97219a83469e4b9990702ec2380b61f1f1a014de337c8e5f231d449e96520a4d353f317affe2d75548d898414b603b72ff009bd4";
            const string password = "16a855c85ee6b1a01c56ba10e86f64473e55980c98510db26380b923ded1290da39825773b657a149408e4060cedab964c69342449c6a71ce2f5b98ad3de1243";

            if (LiczSha512(login.Text).Equals(user) & LiczSha512(haslo.Text).Equals(password))
            {
                IsOk = true;
                Close();
            }
            else
            {
                IsOk = false;
                Wyjatki.Komunikat("Błędne hasło lub login.", "Błąd logowania.", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void AnulujClick(object sender, EventArgs e)
        {
            IsOk = false;
            Application.Exit();
        }

        private void CheckKeys(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.Enter)
            {
                ZalogujClick(this, EventArgs.Empty);
                e.KeyChar = (char)0;
            }
        }

        private static String LiczSha512(String input)
        {
            using (var sha = SHA512.Create())
            {
                var hashB = sha.ComputeHash(Encoding.UTF8.GetBytes(input));

                var sBuilder = new StringBuilder();

                foreach (byte b in hashB)
                {
                    sBuilder.Append(b.ToString("x2"));
                }

                return sBuilder.ToString();
            }
        }

        private void WczytajPlik()
        {
            try
            {
                const string plik = "loguj.txt";

                if (File.Exists(plik))
                {
                    using (var sr = new StreamReader(plik))
                    {
                        login.Text = sr.ReadLine();
                        haslo.Text = sr.ReadLine();
                    }
                }
            }
            catch { }
        }
    }
}
